package com.tian.service.impl;

import com.tian.message.SendEmailMessage;
import com.tian.service.SendEmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-08-13 22:15
 * {@code @version:} 1.0
 */
@Slf4j
@Service("sendEmailSimpleMessageService")
public class SendEmailSimpleServiceImpl implements SendEmailService {
    private final JavaMailSender javaMailSender;

    //邮件发送方邮箱
    @Value("${spring.mail.username}")
    private String MailSender;

    public SendEmailSimpleServiceImpl(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @Override
    public Boolean sendEmail(SendEmailMessage sendEmailMessage){
        String mailRecipient = sendEmailMessage.getRecipientEmail();
        String subject = sendEmailMessage.getTitle();
        String messageText = sendEmailMessage.getContent();
        //1、创建邮件对象（设置参数后提交）
        SimpleMailMessage message = new SimpleMailMessage();
        //2、设置主题
        message.setSubject(subject);
        //3、设置邮件发送者
        message.setFrom(MailSender);
        //4、设置邮件接受者，多个接受者传参为数组格式
        message.setTo(mailRecipient);
        //5、设置邮件正文（邮件的正式内容）
        message.setText(messageText);
        //6、发送邮件
        try {
            javaMailSender.send(message);
            log.info("文本邮件已发送成功");
            return true;
        } catch (MailException e) {
            log.error("sendSimpleMail 邮件发送失败：{}", e.getMessage());
            return false;
        }
    }
}
